<?php

namespace App\Models;

use App\Models\Scope\OnSaleScope;
use App\Models\Scope\ShowScope;
use Illuminate\Database\Eloquent\Model;

class ProductCate extends Model
{
    protected static function boot()
    {
        parent::boot();

        //查询作用域
        static::addGlobalScope(new OnSaleScope());
    }

    protected $table = 'product_cates';

    protected $hidden = [
        'level', 'is_directory', 'sort', 'is_show', 'created_at', 'updated_at', 'path'
    ];

    public function children(){
        return $this->hasMany(get_class($this),'parent_id');
    }

    public function getAllChildren()
    {
        $result = [];
        $children = $this->children;

        foreach ($children as $child) {
            $result[] = $child;

            $childResult = $child->getAllChildren();
            foreach ($childResult as $subChild) {
                $result[] = $subChild;
            }
        }

        return $result;
    }

    public function getImageAttribute($value)
    {
        if($value) {
            return $this->attributes['image'] = config('upload.ossUrl').$value;
        }else{
            return $this->attributes['image'] = '';
        }
    }
}
